import { Button, Form, Input, message, Image } from 'antd';
import { FC, useRef, useState } from 'react';
import { addBannerApi } from '@/api/banner';
import { history } from 'umi';

const Index: FC = () => {
  // const imgUrl = useRef('');
  const [imgUrl, setImgUrl] = useState('');

  const onFinish = (values: any) => {
    // console.log('Success:', { ...values, img: imgUrl.current });
    addBannerApi({ ...values, img: imgUrl }).then((res) => {
      if (res) {
        message.success(res.message);
        history.push('/index/banner/list');
      }
    });
  };

  const fileChange = (event: any) => {
    // event.target.files[0]表示图片信息
    // console.log(event.target.files[0]);

    // 将图片转成base64的格式
    const reader = new FileReader();
    reader.readAsDataURL(event.target.files[0]);
    reader.onload = function (e: any) {
      // 记录读取后的图片
      // console.log(e.target.result);
      setImgUrl(e.target.result);
    };
  };

  return (
    <div>
      <Form
        name="basic"
        style={{ maxWidth: 600 }}
        onFinish={onFinish}
        autoComplete="off"
      >
        <Form.Item
          name="link"
          rules={[{ required: true, message: 'Please input your username!' }]}
        >
          <Input placeholder="链接地址" />
        </Form.Item>

        <Form.Item
          name="alt"
          rules={[{ required: true, message: 'Please input your username!' }]}
        >
          <Input placeholder="提示信息" />
        </Form.Item>

        <Form.Item
          name="image"
          rules={[{ required: true, message: 'Please input your username!' }]}
        >
          <Input type="file" onChange={fileChange} />
        </Form.Item>

        <Form.Item>
          <Button type="primary" htmlType="submit">
            Submit
          </Button>
        </Form.Item>
      </Form>

      <Image src={imgUrl}></Image>
    </div>
  );
};

export default Index;
